//
// Created by lfm on 25-4-19.
//
#include "BookManager.h"
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
const string BookManager::BOOK_DATA_FILE = "/home/lfm/code/cppstudy/BookManagement/books.dat";


// 构造函数，初始化时加载图书数据
BookManager::BookManager()
{
    loadFromFile();
}

// 添加图书，如果图书的ISBN已存在则不添加
void BookManager::addBook(const Book &book)
{
    if (findBook(book.getIsbn()))
    {
        return; // ISBN已存在
    }
    books.push_back(book);
    saveToFile();
}

// 根据ISBN删除图书，删除成功返回true，否则返回false
bool BookManager::deleteBook(const string &isbn)
{
    for (auto it = books.begin(); it != books.end(); ++it)
    {
        if (it->getIsbn() == isbn)
        {
            books.erase(it);
            saveToFile();
            return true;
        }
    }
    return false;
}

// 根据ISBN修改图书信息，修改成功返回true，否则返回false
bool BookManager::modifyBook(const string &isbn, const Book &newBook)
{
    Book *book = findBook(isbn);
    if (book)
    {
        *book = newBook;
        saveToFile();
        return true;
    }
    return false;
}

// 根据ISBN查找图书，找到返回图书指针，否则返回nullptr
Book *BookManager::findBook(const string &isbn)
{
    for (auto &book : books)
    {
        if (book.getIsbn() == isbn)
        {
            return &book;
        }
    }
    return nullptr;
}

// 显示所有图书信息
void BookManager::displayBooks() const
{
    system("clear");
    cout << "------------------- 图书列表 -------------------" << endl;
    if (books.empty())
    {
        cout << "没有图书信息" << endl;
        return;
    }
    for (const auto &book : books)
    {
        cout << "ISBN: " << book.getIsbn()
             << "\t书名: " << book.getTitle()
             << "\t作者: " << book.getAuthor()
             << "\t剩余数量: " << book.getQuantity()<< endl;
    }
    cout << "----------------------------------------------" << endl;
    // system("pause");
}

// 将图书数据保存到文件
void BookManager::saveToFile() const
{
    ofstream file(BOOK_DATA_FILE, ios::out);
    if (file.is_open())
    {
        for (const auto &book : books)
        {
            file << book.getIsbn() << " "
                 << book.getTitle() << " "
                 << book.getAuthor() << " "
                 << book.getQuantity() << endl;
        }
        file.close();
    }
}

// 从文件加载图书数据
void BookManager::loadFromFile()
{
    books.clear();
    ifstream file(BOOK_DATA_FILE, ios::in);
    if (file.is_open())
    {
        string isbn, title, author;
        int quantity;//读取数量
        bool available;
        while (file >> isbn >> title >> author >> quantity)
        {
            books.emplace_back(isbn, title, author,quantity);
        }
        file.close();
    }
}



